Expand description
A generic connection pool with async/await support.
Opening a new database connection every time one is needed is both inefficient and can lead to resource exhaustion under high traffic conditions. A connection pool maintains a set of open connections to a database, handing them out for repeated use.
mobc is agnostic to the connection type it is managing. Implementors of the
Manager
trait provide the database-specific logic to create and
check the health of connections.
§Example
Using an imaginary “foodb” database.
use mobc::{Manager, Pool, async_trait};
#[derive(Debug)]
struct FooError;
struct FooConnection;
impl FooConnection {
async fn query(&self) -> String {
"nori".to_string()
}
}
struct FooManager;
#[async_trait]
impl Manager for FooManager {
type Connection = FooConnection;
type Error = FooError;
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
Ok(FooConnection)
}
async fn check(&self, conn: Self::Connection) -> Result<Self::Connection, Self::Error> {
Ok(conn)
}
}
#[tokio::main]
async fn main() {
let pool = Pool::builder().max_open(15).build(FooManager);
let num: usize = 10000;
let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(16);
for _ in 0..num {
let pool = pool.clone();
let mut tx = tx.clone();
tokio::spawn(async move {
let conn = pool.get().await.unwrap();
let name = conn.query().await;
assert_eq!(name, "nori".to_string());
tx.send(()).await.unwrap();
});
}
for _ in 0..num {
rx.recv().await.unwrap();
}
}
§Metrics
Mobc uses the metrics crate to expose the following metrics
- Active Connections - The number of connections in use.
- Idle Connections - The number of connections that are not being used
- Wait Count - the number of processes waiting for a connection
- Wait Duration - A cumulative histogram of the wait time for a connection
Modules§
- A batteries included runtime for applications using mobc. Mobc does not implement runtime, it simply exports runtime.
Structs§
- A builder for a connection pool.
- A smart pointer wrapping a connection.
- A generic connection pool.
- Information about the state of a
Pool
.
Enums§
- The error type returned by methods in this crate.
Traits§
- A trait which provides connection-specific functionality.
Functions§
- Spawns a new asynchronous task.